package com.example.demo.wsservice;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.example.demo.config.SpringBeanContext;
import com.example.demo.pojo.GroupMessage;
import com.example.demo.pojo.PrivateMsg;
import com.example.demo.util.HttpSendUtil;
import jakarta.websocket.OnError;
import jakarta.websocket.OnMessage;
import jakarta.websocket.Session;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Component
@ServerEndpoint("/ws")
@Slf4j
public class WebsocketService {


    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("message:{}",message);
        JSONObject jsonObject = JSON.parseObject(message);
        HttpSendUtil bean = SpringBeanContext.getBean(HttpSendUtil.class);
        if ("group".equals(jsonObject.getString("message_type"))) {
            GroupMessage groupMessage = JSON.parseObject(message, GroupMessage.class);
            log.info(" groupId: {} ,sender:{},群消息:{}",groupMessage.getGroup_id(),groupMessage.getSender().getUser_id(),groupMessage.getRaw_message());
            bean.sendGroupMsg(String.valueOf(groupMessage.getGroup_id())," group resp:"+groupMessage.getRaw_message());
        } else if ("private".equalsIgnoreCase(jsonObject.getString("message_type"))) {
            PrivateMsg privateMsg = JSON.parseObject(message, PrivateMsg.class);
            log.info(" sender: {},私聊消息:{}",privateMsg.getSender().getUser_id(),privateMsg.getRaw_message());
            bean.sendPrivateMsg(String.valueOf(privateMsg.getSender().getUser_id()),"resp:"+privateMsg.getRaw_message());
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error(error.getMessage(),error);
    }

}
